<template>
    <div class="page-content">
        <h3>秒杀活动列表</h3>
        <el-row>
            <el-col :xs="24" :sm="12" :lg="6" class="el-col2">
                <el-button @click="showDialog('add')" v-ripple>新增活动</el-button>
            </el-col>
            <el-col :xs="24" :sm="12" :lg="3">
                <el-form :model="searchForm">
                    <el-form-item prop="activityName">
                        <el-input placeholder="请输入活动名称" v-model="searchForm.activityName" @blur="getData"></el-input>
                    </el-form-item>
                </el-form>
            </el-col>
        </el-row>

        <art-table :data="tableData" :loading="tableLoading" :currentPage="pageNum" :pageSize="pageSize"
            :total="pageTotal" @current-change="currentChange" @size-change="sizeChange">
            <template #default>
                <el-table-column label="活动名称" prop="activityName" align="center" />
                <el-table-column label="秒杀时间" #default="scope" align="center">
                    {{ scope.row.startTime }}~{{ scope.row.endTime }}
                </el-table-column>
                <el-table-column label="参与人数" align="center">
                    <template #default="scope">
                        {{ scope.row.receiveQuantity }}/ {{ scope.row.issueQuantity === 0 ? '无限制' :
                            scope.row.issueQuantity }}
                    </template>
                </el-table-column>
                <el-table-column label="活动状态" prop="activityStatus" align="center">
                    <template #default="scope">
                        <el-tag type="primary" v-if="scope.row.activityStatus === 1">进行中</el-tag>
                        <el-tag type="info" v-if="scope.row.activityStatus === 0">未开始</el-tag>
                        <el-tag type="warning" v-if="scope.row.activityStatus === 2">已结束</el-tag>
                        <el-tag type="danger" v-if="scope.row.activityStatus === 3">已停用</el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="添加时间" prop="createTime" align="center">
                    <template #default="scope">
                        {{ formatDate(scope.row.createTime) }}
                    </template>
                </el-table-column>
                <el-table-column fixed="right" label="操作" width="150px" align="center">
                    <template #default="scope">
                        <button-table type="edit" @click="buttonMoreClick(scope.row)" />
                        <button-table type="delete" @click="deleteRole(scope.row.id)" />
                    </template>
                </el-table-column>
            </template>
        </art-table>

        <el-dialog v-model="dialogVisible" :title="dialogType === 'add' ? '新增秒杀活动' : '编辑秒杀活动'" width="50%"
            :close-on-click-modal="false">
            <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
                <el-form-item label="活动名称：" prop="activityName" style="width: 500px">
                    <el-input v-model="form.activityName" placeholder="请输入活动名称" />
                </el-form-item>
                <el-form-item label="秒杀时间名称：" style="width: 500px">
                    <el-date-picker v-model="fixedTime" type="datetimerange" range-separator="~"
                        start-placeholder="开始时间" end-placeholder="结束时间" @change="validTimeChange" />
                </el-form-item>
                <div v-if="shoppingList.length">
                    <div v-for="(item, index) in shoppingList" :key="index">
                        <!-- 秒杀价校验必填 -->
                        <el-form-item label="秒杀商品" required :error="item._error">
                            <div class="flash-sale-section">
                                <div class="price-table">
                                    <div class="table-header">
                                        <span>商品名称</span>
                                        <span>原价(元)</span>
                                        <span>秒杀价(元)</span>
                                        <span>操作</span>
                                    </div>
                                    <div class="table-row">
                                        <div class="price-cell">
                                            {{ item.name }}
                                        </div>
                                        <div class="price-cell">
                                            <el-input v-model="item.originalPrice" style="width: 130px;" disabled />
                                        </div>
                                        <div class="price-cell">
                                            <el-input v-model="item.activityPrice" placeholder="输入秒杀价格"
                                                style="width: 130px;" :class="{ 'is-error': item._error }" />
                                        </div>
                                        <div class="price-cell action-link" @click="remove(index)">
                                            移除
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </el-form-item>
                    </div>
                </div>
                <el-form-item label="选择商品" required>
                    <el-button @click="addShopping">添加商品</el-button>
                </el-form-item>
                <el-form-item label="备注" style="width: 500px">
                    <el-input v-model="form.remark" placeholder="请输入备注" />
                </el-form-item>
                <el-form-item label="启用状态" prop="status">
                    <el-switch v-model="form.status" :inactive-value="0" :active-value="1" />
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="handleSubmit(formRef)">提交</el-button>
                </div>
            </template>
        </el-dialog>
        <el-dialog title="活动商品" width="40%" v-model="activeShopDialog" :close-on-click-modal="false">
            <art-table :data="shopData" selection :loading="shopLoading" :currentPage="shopPageNum"
                :pageSize="shopPageSize" :total="shopPageTotal" @current-change="shopCurrentChange"
                @size-change="shopSizeChange" @selection-change="handleSelectionChange">
                <template #default>
                    <el-table-column label="ID" prop="id" align="center" />
                    <el-table-column label="班型信息" prop="typename">
                        <template #default="scope">
                            <div class="title_box">
                                <div class="title_box_left" v-if="scope.row.image">
                                    <img class="tableimg" :src="scope.row.image" />
                                </div>
                                <div class="title_box_right">
                                    <div class="bankcont_title" v-if="scope.row.name">
                                        <div class="bankcont_title_text">{{ scope.row.name }}</div>
                                    </div>
                                    <div style="clear: both"></div>
                                    <div class="cartcont" v-if="scope.row.tags">
                                        <el-button v-for="tag in scope.row.tags.split(',')" :key="tag" round
                                            size="small">
                                            {{ tag }}
                                        </el-button>
                                    </div>
                                </div>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column label="售价（元）" prop="price">
                        <template #default="scope"> {{ scope.row.price }} </template>
                    </el-table-column>
                </template>
            </art-table>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitShopping">确认</el-button>
                    <el-button @click="activeShopDialog = false">
                        取消
                    </el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { activityGetPage, addSaleActive, delSaleActive, editSaleActive, editSaleActiveState } from '@/api/marketing'
import { StudentClassTypeLis } from '@/api/driverSchoolApi'

const dialogVisible = ref(false)
const fixedTime = ref<[Date, Date] | []>([])
const formRef = ref<FormInstance>()
const activeShopDialog = ref(false)

const rules = reactive<FormRules>({
    name: [
        { required: true, message: '请输入活动名称', trigger: 'blur' },
        { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
    ],
})

const form = reactive({
    id: '',
    activityName: '',
    // sort: '1',
    status: 1,
    startTime: '',
    endTime: '',
    receiveQuantity: 0,
    activityType: '05',
    remark: ''
})
const searchForm = reactive({
    activityName: ''
})

const tableData = ref([])

const dialogType = ref('add')

const showDialog = (type: string, row?: any) => {
    dialogVisible.value = true
    dialogType.value = type

    if (type === 'edit' && row) {
        // 把表单回显数据设置上
        form.id = row.id || ''
        form.activityName = row.activityName || ''
        form.startTime = row.startTime || ''
        form.endTime = row.endTime || ''
        form.status = row.status
        form.receiveQuantity = row.receiveQuantity || 0
        form.activityType = '05'
        form.remark = row.remark || ''
        fixedTime.value = row.startTime && row.endTime ? [new Date(row.startTime), new Date(row.endTime)] : []
        if (row.activityContentAoList && row.activityContentAoList.length) {
            shoppingList.value = row.activityContentAoList.map((e: any) => {
                let commodity = (e.activityCommodityAoList && e.activityCommodityAoList.length) ? e.activityCommodityAoList[0] : {};
                return {
                    name: commodity.name || '',
                    giftRefIds: e.giftRefIds || '',
                    originalPrice: commodity.price || 0,
                    activityPrice: e.activityPrice || 0,
                    targetType: e.targetType || '01',
                    giftType: e.giftType || '05',
                    _error: ''
                }
            })
        } else {
            shoppingList.value = []
        }

        shoppingData.value = [...shoppingList.value] // 回显同步
    } else {
        form.id = ''
        form.activityName = ''
        // form.sort = '1'
        form.startTime = ''
        form.endTime = ''
        form.remark = ''
        form.status = 1
        form.receiveQuantity = 0
        form.activityType = '05'
        fixedTime.value = []
        // 重置商品列表
        shoppingList.value = []
        shoppingData.value = []
    }
}

const buttonMoreClick = (row: any) => {
    showDialog('edit', row)
}

const deleteRole = (id: string) => {
    ElMessageBox.confirm('确定删除该优惠券吗？', '删除确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error'
    }).then(async () => {
        const res = await delSaleActive(id)
        if (res.code === '00000') {
            ElMessage.success('删除成功')
            getData()
        }
    })
}

// 秒杀价校验必填
const validateActivityPriceRequired = (): boolean => {
    let valid = true;
    if (shoppingList.value && shoppingList.value.length > 0) {
        shoppingList.value.forEach((item: any, index: number) => {
            // 允许非数字0情况时调整下验证逻辑
            if (
                item.activityPrice === undefined ||
                item.activityPrice === null ||
                item.activityPrice === "" ||
                isNaN(Number(item.activityPrice))
            ) {
                valid = false;
                item._error = "请输入必填的秒杀价(数字)";
            } else {
                item._error = "";
            }
        });
    }
    return valid;
};

const handleSubmit = async (formEl: FormInstance | undefined) => {
    if (!formEl) return

    // 秒杀价必填校验
    if (!validateActivityPriceRequired()) {
        ElMessage.error("请输入对应有效的秒杀价格");
        return;
    }

    await formEl.validate(async (valid) => {
        if (valid) {
            const message = dialogType.value === 'add' ? '新增成功' : '修改成功'
            const params = filterEmptyValues(form)

            const activityContentVoList = shoppingList.value.map((e: any) => {
                const { _error, ...rest } = e;
                return {
                    ...rest,
                    originalPrice: Number(e.originalPrice),
                    activityPrice: Number(e.activityPrice)
                }
            })
            // return
            if (form.id) {
                const res = await editSaleActive({ ...params, activityContentVoList }, form.id)
                if (res.code === '00000') {
                    ElMessage.success(message)
                    dialogVisible.value = false
                    getData()
                }
            } else {
                const res = await addSaleActive({ ...params, activityContentVoList })
                if (res.code === '00000') {
                    ElMessage.success(message)
                    dialogVisible.value = false
                    getData()
                }
            }
        }
    })
}

const formatDate = (date: string) => {
    if (!date) return ''
    try {
        return new Date(date)
            .toLocaleString('zh-CN', {
                year: 'numeric',
                month: '2-digit',
                day: '2-digit',
                hour: '2-digit',
                minute: '2-digit',
                second: '2-digit'
            })
            .replace(/\//g, '-')
    } catch (error) {
        console.error('日期格式化错误:', error)
        return ''
    }
}

const tableLoading = ref(false)
const pageNum = ref(1)
const pageSize = ref(10)
const pageTotal = ref(0)

const currentChange = (val: number) => {
    pageNum.value = val
    getData()
}

const sizeChange = (val: number) => {
    pageSize.value = val
    pageNum.value = 1
    getData()
}

const filterEmptyValues = (obj: any) => {
    const result: any = {}
    for (const key in obj) {
        if (obj[key] !== '' && obj[key] !== null && obj[key] !== undefined) {
            result[key] = obj[key]
        }
    }
    return result
}

const getData = async () => {
    tableLoading.value = true
    try {
        const params = filterEmptyValues(searchForm)
        const res = await activityGetPage({
            pageSize: pageSize.value,
            pageNum: pageNum.value,
            activityType: '05',
            ...params
        })
        if (res.code === '00000') {
            tableData.value = res.data.list
            pageTotal.value = res.data.total
        }
    } catch { } finally {
        tableLoading.value = false
    }

}
const validTimeChange = (e: any) => {
    if (e && e.length >= 2) {
        form.startTime = formatDate(e[0])
        form.endTime = formatDate(e[1])
    } else {
        form.startTime = ''
        form.endTime = ''
    }
}

const EditStatus = async (id: string, status: number) => {
    try {
        const res = await editSaleActiveState(id, { status })
        if (res.code === '00000') {
            ElMessage.success('修改成功')
        }
    } catch (e) {
    } finally {
        await getData()
    }
}

const shopPageNum = ref(1)
const shopPageSize = ref(10)
const shopPageTotal = ref(0)
const shopLoading = ref(false)
const shopData = ref([])

const addShopping = () => {
    activeShopDialog.value = true
    getShopList()
}

const shopCurrentChange = (val: number) => {
    shopPageNum.value = val
    getShopList()
}

const shopSizeChange = (val: number) => {
    shopPageSize.value = val
    shopPageNum.value = 1
    getShopList()
}

const getShopList = async () => {
    shopLoading.value = true
    try {
        const res = await StudentClassTypeLis({
            pageNum: shopPageNum.value,
            pageSize: shopPageSize.value,
        })
        if (res.code === '00000') {
            shopData.value = res.data.list
            shopPageTotal.value = res.data.total
        }
    } catch {

    } finally {
        shopLoading.value = false
    }
}

const shoppingData = ref<any>([])
const handleSelectionChange = (e: any) => {
    if (e && e.length) {
        shoppingData.value = e.map((item: any) => {
            return {
                name: item.name || '',
                giftRefIds: item.id || '',
                originalPrice: item.price || 0,
                activityPrice: '0',
                targetType: '01',
                giftType: '05',
                _error: ''
            }
        })
    } else {
        shoppingData.value = []
    }
}
const shoppingList = ref<any>([])
const submitShopping = () => {
    shoppingList.value = shoppingData.value
    activeShopDialog.value = false
}

const remove = (i: number) => {
    shoppingList.value.splice(i, 1)
}

onMounted(() => {
    getData()
})
</script>

<style lang="scss" scoped>
.page-content {
    .svg-icon {
        width: 1.8em;
        height: 1.8em;
        overflow: hidden;
        vertical-align: -8px;
        fill: currentcolor;
    }

    h3 {
        font-weight: bold;
        margin-bottom: 20px;
    }
}

.title_box_left {
    float: left;
    width: 4.5rem;
    height: 4.5rem;
    border-radius: 0.5rem;
    overflow: hidden;
    margin-right: 1rem;

    .tableimg {
        width: 100%;
        height: 100%;
    }
}

.title_box_right {
    float: right;
    float: left;
}

.bankcont_title_text {
    height: 2rem;
    margin-top: 0.3rem;
}

:deep(.el-row) {
    justify-content: space-between;
}

.flash-sale-section {
    width: 900px;

    .info-text {
        color: #666;
        font-size: 14px;
        margin-bottom: 16px;
        line-height: 1.5;
    }

    .product-table,
    .price-table {
        border: 1px solid #e4e7ed;
        border-radius: 4px;
        overflow: hidden;

        .table-header {
            background-color: #f5f7fa;
            display: grid;
            grid-template-columns: 1fr 1fr 1fr 1fr;
            padding: 12px 16px;
            font-weight: 500;
            color: #303133;
            border-bottom: 1px solid #e4e7ed;

            span {
                text-align: center;
            }
        }

        .table-row {
            display: grid;
            padding: 16px;
            grid-template-columns: 1fr 1fr 1fr;
            align-items: center;
            border-bottom: 1px solid #f0f0f0;
            background-color: #fff;

            &:last-child {
                border-bottom: none;
            }

        }
    }

    .price-table {
        .table-header {
            grid-template-columns: repeat(4, 1fr);
        }

        .table-row {
            grid-template-columns: repeat(4, 1fr);

            .price-cell {
                text-align: center;
                display: flex;
                align-items: center;
                justify-content: center;
                flex-direction: column;
                gap: 8px;

                .price-type-help {
                    font-size: 12px;
                    color: #909399;
                    line-height: 1.4;
                    text-align: center;
                    margin-top: 4px;
                }
            }

            .is-error input {
                border-color: #f56c6c !important;
            }
        }
    }

    .action-link {
        color: #409eff;
        cursor: pointer;
        font-size: 14px;

        &:hover {
            text-decoration: underline;
        }
    }
}
</style>